import { UserTreasury } from '@/store/treasurySlice'
import { get } from 'lodash'
import { CdnImage } from '@/ui-components'
import { View } from '@tarojs/components'
import { useMemo } from 'react'
import dayjs from 'dayjs'
import { UserTreasuryCheckin } from '@/types'


interface CheckinProps {
  userTreasury: UserTreasury
  userCheckin: UserTreasuryCheckin
  onCheckin: () => void
}

const Checkin = ({ userTreasury, userCheckin, onCheckin }: CheckinProps) => {
  const isCheckinEnable = useMemo(() => {
    if (!get(userTreasury, 'treasuryCheckin.enabled')) {
      return false
    }
    const startTime = get(userTreasury, 'treasuryCheckin.startTime')
    const endTime = get(userTreasury, 'treasuryCheckin.endTime')
    if (!startTime || !endTime) {
      return false
    }
    if (dayjs().isBefore(startTime) || dayjs().isAfter(endTime)) {
      return false
    }
    return true
  }, [userTreasury])

  const isCheckin = useMemo(() => {
    if (!userCheckin) {
      return false
    }
    const lastCheckinTime = get(userCheckin, 'lastCheckinTime')
    if (!lastCheckinTime) {
      return false
    }
    if (dayjs().isSame(lastCheckinTime, 'day')) {
      return true
    }
    return false
  }, [userCheckin])

  if (isCheckinEnable) {
    return (
      <View>
        <CdnImage
          src={isCheckin ? '/common/checkin/checkin.png' : '/common/checkin/uncheckin.png'}
          className='image-128'
          onClick={onCheckin}
        />
      </View>
    )
  }
}

export default Checkin